package com.itechart.watchfacts.controller;

import com.itechart.watchfacts.domain.Brand;
import com.itechart.watchfacts.service.GeneralService;
import org.hibernate.exception.ConstraintViolationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * Created by IntelliJ IDEA.
 * User: E.Krasnotschek
 * Date: 7/30/13
 * Time: 8:11 AM
 * To change this template use File | Settings | File Templates.
 */
@Controller
@RequestMapping(value = "/brand")
public class BrandController extends ControllerBase<Brand>{

    public BrandController(){
        listView =  "brand";
        listUrl = "/brand/list";
        modelAttrCreate = "brand";
        modelAttrList = "brandList";
    }

    @Autowired
    @Qualifier("brandServiceImpl")
    public void setService(GeneralService<Brand> service){
        this.service = service;
    }

    @Override
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list(Model model){
        model.addAttribute(modelAttrCreate, new Brand());
        model.addAttribute(modelAttrList, service.list());

        return listView;
    }

    @Override
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public String create(Model model){
        return list(model);
    }

    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public String create(@ModelAttribute(value = "brand")Brand brand){
        try{
            service.create(brand);
        }catch (ConstraintViolationException e){
            //handle the situation when the new brand duplicates existing one
        }
        return "redirect:"+ listUrl;
    }

    @Override
    @RequestMapping(value="/delete/{id}")
    public String delete(@PathVariable("id") int id){
        service.delete(id);

        return "redirect:" + listUrl;
    }
}
